<template>
  <div class="app-container">
    <div class="detail-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/attraction/' }">
          <i
            class="el-icon-arrow-left"
            style="font-size: 15px; font-weight: bold; padding-right: 3px"
          ></i
          >{{ name }}触发数据</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="data-row">
          <div class="data-row-header">
            <div class="data-row-header-title">{{ name }}热度图谱</div>
            <div class="data-row-header-time">
              <el-date-picker
                v-model="timeRange1"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @change="handleDateChange"
              >
              </el-date-picker>
            </div>
          </div>
          <div class="chart-container heat-map-chart" ref="chartContainer"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="data-row">
          <div class="data-row-header">
            <div class="data-row-header-title">{{ name }}收听率和完播率排名</div>
            <div class="data-row-header-time">
              <el-date-picker
                v-model="timeRange2"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @change="handleDateChange"
              >
              </el-date-picker>
            </div>
          </div>
          <div class="rate-charts">
            <div class="rate-chart-title">收听率排名</div>
            <div class="chart-container" ref="listenRateChart"></div>
            <div class="rate-chart-title complete-rate-chart-title">完播率排名</div>
            <div class="chart-container" ref="completeRateChart"></div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { getAttractionStats, getAttractionRankStats } from '@/api/attraction'

// 注册必要的组件
echarts.use([
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer
])

export default {
  name: 'dataList',
  components: {},
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      attraction_id: '', // 景点ID
      name: '',
      listLoading: false,
      chartInstance: null,
      listenRateChartInstance: null,
      completeRateChartInstance: null,
      timeRange1: [],
      timeRange2: [],
      attractionData: [],
      listenRateData: [],
      completeRateData: [],
      colors: []
    }
  },
  mounted() {
    this.attraction_id = this.$route.query.id
    this.name = this.$route.query.name
    this.initChart()
    this.fetchData()
  },
  methods: {
    initChart() {
      // 获取DOM容器
      const chartDom = this.$refs.chartContainer
      // 初始化echarts实例
      this.chartInstance = echarts.init(chartDom)
      // 设置图表大小
      this.chartInstance.resize({
        width: 'auto',
        minHeight: 600
      })

      // 初始化收听率图表
      const listenRateChartDom = this.$refs.listenRateChart
      this.listenRateChartInstance = echarts.init(listenRateChartDom)
      this.listenRateChartInstance.resize({
        width: 'auto',
        minHeight: 300
      })

      // 初始化完播率图表
      const completeRateChartDom = this.$refs.completeRateChart
      this.completeRateChartInstance = echarts.init(completeRateChartDom)
      this.completeRateChartInstance.resize({
        width: 'auto',
        minHeight: 300
      })
    },
    fetchData() {
      this.listLoading = true
      // 构建请求参数
      const params = {
        attraction_id: this.attraction_id
      }
      const params1 = {}
      if (this.timeRange1 && this.timeRange1.length === 2) {
        params1.start_date = this.formatDate(this.timeRange1[0])
        params1.end_date = this.formatDate(this.timeRange1[1])
      }
      const params2 = {}
      if (this.timeRange2 && this.timeRange2.length === 2) {
        params2.start_date = this.formatDate(this.timeRange2[0])
        params2.end_date = this.formatDate(this.timeRange2[1])
      }
      console.log('params', params)

      getAttractionStats({
        ...params,
        ...params1
      })
        .then((res) => {
          this.listLoading = false

          this.updateChart(res.data.view_num_stats)
        })
        .catch(() => {
          this.listLoading = false
        })

      getAttractionRankStats({
        ...params,
        ...params2
      }).then((res) => {
        this.updateListenRateChart(res.data.play_rate_stats)
        this.updateCompleteRateChart(res.data.finished_rate_stats)
      })
    },
    updateChart(data) {
      // 对数据进行倒序处理
      const reversedData = {
        attraction: [...data.attraction].reverse(),
        nums: [...data.nums].reverse(),
        color: [...data.color].reverse()
      }

      // 配置图表选项
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '收听人数',
          nameLocation: 'middle',
          nameGap: 25,
          min: 1,
          splitLine: {
            show: false // 隐藏x轴网格线
          },
          axisLine: {
            show: false // 保留坐标轴线
          }
        },
        yAxis: {
          type: 'category',
          data: reversedData.attraction,
          axisTick: {
            alignWithLabel: true
          }
        },
        series: [
          {
            name: '收听人数',
            type: 'bar',
            barWidth: 25,
            data: reversedData.nums,
            itemStyle: {
              // 根据数据值设置不同的颜色
              color: (params) => {
                // 颜色数组，从高到低
                return reversedData.color[params.dataIndex] || '#7ac79d'
              }
            }
          }
        ]
      }

      // 使用配置项设置图表
      this.chartInstance.setOption(option)
    },
    updateListenRateChart(data) {
      // 对数据进行倒序处理
      const reversedData = {
        attraction: [...data.attraction].reverse(),
        nums: [...data.nums].reverse(),
        color: [...data.color].reverse()
      }

      // 配置收听率图表选项
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '8%', // 从4%增加到8%，给右侧更多空间
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '%',
          nameLocation: 'middle',
          nameGap: 25,
          max: 100,
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          }
        },
        yAxis: {
          type: 'category',
          data: reversedData.attraction,
          axisTick: {
            alignWithLabel: true
          }
        },
        series: [
          {
            name: '收听率',
            type: 'bar',
            barWidth: 25,
            data: reversedData.nums,
            itemStyle: {
              color: (params) => {
                return reversedData.color[params.dataIndex] || '#7ac79d'
              }
            }
          }
        ]
      }

      this.listenRateChartInstance.setOption(option)
    },
    updateCompleteRateChart(data) {
      // 对数据进行倒序处理
      const reversedData = {
        attraction: [...data.attraction].reverse(),
        nums: [...data.nums].reverse(),
        color: [...data.color].reverse()
      }

      // 配置完播率图表选项
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '%',
          nameLocation: 'middle',
          nameGap: 25,
          max: 100,
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          }
        },
        yAxis: {
          type: 'category',
          data: reversedData.attraction,
          axisTick: {
            alignWithLabel: true
          }
        },
        series: [
          {
            name: '完播率',
            type: 'bar',
            barWidth: 25,
            data: reversedData.nums,
            itemStyle: {
              color: (params) => {
                return reversedData.color[params.dataIndex] || '#7ac79d'
              }
            }
          }
        ]
      }

      this.completeRateChartInstance.setOption(option)
    },
    handleDateChange() {
      this.fetchData()
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped lang="less">
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.data-row-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  width: 95%;
}
.data-row-header-title {
  font-size: 16px;
  font-weight: bold;
}
.data-row-header-time {
  font-size: 12px;
  color: #666;
}
.chart-container {
  width: 100%;
  height: 600px;
}
.heat-map-chart {
  border-right: 1px solid #e5e5e5;
}
.rate-charts {
  margin-top: 20px;
}
.rate-chart-title {
  font-size: 14px;
  font-weight: bold;
  margin-top: 20px;
  margin-bottom: 10px;
}
.rate-charts .chart-container {
  min-height: 300px;
}
.complete-rate-chart-title {
  padding-top: 20px;
  border-top: 1px solid #e5e5e5;
}
</style>
